package com;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JHTTP {

    private final static Logger logger = Logger.getLogger(JHTTP.class.getCanonicalName());

    private final static int DEFAULT_PORT = 1118;

    private final static int THREAD_NUM = 50;

    private final static String INDEX_FILE = "index.html";

    private final File rootDirectory;

    private final int port;

    public JHTTP(File rootDirectory, int port) throws IOException {
        if(!rootDirectory.isDirectory())
            throw new IOException(rootDirectory + " is not a directory.");
        this.rootDirectory = rootDirectory;
        this.port = port;
    }

    public void start(){

        ExecutorService tp = Executors.newFixedThreadPool(THREAD_NUM);

        try (ServerSocket server = new ServerSocket(port)){

            while (true){

                try {

                    Socket conn = server.accept();

                    logger.info(conn + " connected to this server.");

                    logger.info("document root is " + rootDirectory);

                    Runnable r = new RequestProcessor(rootDirectory,INDEX_FILE,conn);

                    tp.submit(r);

                }catch (IOException ex){
                    logger.log(Level.WARNING,"error accepting connection",ex);
                }

            }

        } catch (IOException e) {
            logger.log(Level.SEVERE,"error eastablished server",e);
        }

    }

    public static void main(String[] args) {

        File docroot;

        try {
            docroot = new File(args[0]);
        }catch (ArrayIndexOutOfBoundsException ex){
            System.out.println("Usage: java JHTTP docroot port");
            return;
        }

        int port;

        try {
            port = Integer.parseInt(args[1]);
            if(port<1 || port>65535) port = DEFAULT_PORT;
        }catch (RuntimeException ex){
            port = DEFAULT_PORT;
        }

        try {
            JHTTP webserver = new JHTTP(docroot,port);

            webserver.start();

        } catch (IOException e) {
            logger.log(Level.SEVERE,"couldn't start server",e);
        }

    }


}
